package com.cross.plain;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

import com.cross.core.AbstractReader;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;
import com.cross.util.StringUtils;
/**
 * 文本读取器
 * @author wu
 *
 */
public class SimplePlainReader extends AbstractReader {

	private File file;
	private String split = ",";
	private LineNumberReader reader;

	public SimplePlainReader(File file, String split) {
		this.file = file;
	}

	public SimplePlainReader(File file) {
		this.file = file;
	}

	private void init() throws FileNotFoundException {
		reader = new LineNumberReader(new FileReader(file));
		header = createHeader();
	}

	@Override
	protected boolean nextRow() {
		return nextRowImpl();
	}

	private boolean nextRowImpl() {
		String line = null;
		try {
			line = reader.readLine();
		} catch (IOException e) {
			return false;
		}
		if (StringUtils.isBlank(line)) {
			return false;
		}
		currentRow = toRow(line);
		return null != currentRow;
	}

	private Header createHeader(){
		String line = null;
		try {
			line = reader.readLine();
		} catch (IOException e) {
			return null;
		}
		if (StringUtils.isBlank(line)) {
			return null;
		}
		Header header = new Header();
		String[] titles = line.split(split);
		for(int i=0; i<titles.length; i++){
			header.add(new Column(i,titles[i],"string"));
		}
		return header;
	}
	
	private Row toRow(String line) {
		Row row = new Row();
		String[] items = line.split(split);
		for (String i : items) {
			row.append(toItem(i, "string"));
		}
		return row;
	}

	private Item toItem(String value, String type) {
		return new Item(value, type);
	}

	@Override
	public void close() {
		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
